#include "Comm.h"

/*--------------------------------------------------------------------*/
void Comm::ServerConnectionRecvr(void* threadParams) {
	portIPSim* args = (portIPSim*)threadParams;
	try {
		int StartingPortPool = ServerStartingPort;
		string command;
		//TODO: Not sure if i need to disconnect clients or how to do it
		SocketServer s = SocketServer(ServerStartingPort, 10, BlockingSocket);
		//Continually listen for new connections
		while(true) {
			cout << "\nGameServer (ip: " << Utils::getLocalIP() << ") waiting for Control connection..." << endl;

			Socket* client = s.Accept();
			cout << "Connection accepted!" << endl;
			//We are connected, now what do they want?
			command = client->ReceiveLine();
			cout << "COMMAND = " + command << endl;
			if(command == "JoinGame\n") {
				//Send two port numbers back first to listen on the second to send on.  Also server to increment at same time
				int senderPort = ++StartingPortPool;
				int recvrPort = ++StartingPortPool;
				
				/***  CHANGE THESE TWO LINES TO MAKE LOCAL OR LOOPBACK !  ***/
				string localIP = Utils::getLocalIP();
				//string localIP = "127.0.0.1";
				/************************************************************/

				//Create the Arg Structures for the two Threads we will spawn
				portIPSim* senderArgs = new portIPSim(senderPort, localIP, args->gameSim);
				portIP* recvrArgs = new portIP(recvrPort, localIP);

				char portBuffer[10];
				string sSenderPort(itoa(senderPort, portBuffer, 10));
				string sRecvrPort(itoa(recvrPort, portBuffer, 10));

				string ports = (sSenderPort + "," + sRecvrPort);
				cout << ports << endl;
				client->SendLine(ports);
				//Spawn a new thread on the 
				//StartingPortPool;
				DWORD SenderThreadId;
				DWORD RecvrThreadId;

				//Launch a recvr thread for the client
				HANDLE ServerRecvrThread = CreateThread(NULL,0,
					(LPTHREAD_START_ROUTINE)Comm::ServerRecvr,recvrArgs,0,&RecvrThreadId);
				if ( ServerRecvrThread == NULL ) { cout << "ServerRecr Creation Failed!" << endl; } else { cout << "Spawn Server Recvr Thread" << endl; }

				//Launch a sender for the client
				HANDLE ServerSenderThread = CreateThread(NULL,0,
					(LPTHREAD_START_ROUTINE)Comm::ServerSender,senderArgs,0,&SenderThreadId);
				if ( ServerSenderThread == NULL ) { cout << "ServerSender Creation Failed!" << endl; } else { cout << "Spawn Server Sending Thread" << endl; }
			} else if(command =="SomeShit") {
				//Do something else
			}
		}
		s.Close();
	}
	catch ( char* str ) { cerr << str << endl; } 
	catch ( string str ) { cerr << str << endl; } 
	catch ( ... ) { cerr << "unhandled exception\n"; }
}

/*--------------------------------------------------------------------*/
